<template>
  <div class="personalInfo">
    <van-nav-bar
        :title="$t('personal_info')"
        left-arrow
        @click-left="$router.push($route.query.backName)"
    />
    <!--     身份信息-->
    <div style="padding: 10px">
      <div class="content_list">
        <!--      贷款用途-->
        <div class="content_item" @click="purposeLoanClick" v-if="resourcesShow['loanUse'] === 1">
          <div>
            <img class="image" src="../../assets/icon_loan_use.png">
            <span class="text">{{ $t('loan_purpose') }}</span>
          </div>
          <div class="select_right">
            <span v-if="purposeLoanText" class="select_right_text" style=" color: #686666;">{{ purposeLoanText }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_loan_purpose') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--      住宅地址-->
        <div class="content_item" @click="addressClick" v-if="resourcesShow['liveDetailedAddress'] === 1">
          <div>
            <img class="image" src="../../assets/icon_zhuzhai.png">
            <span class="text">{{ $t('address_home') }}</span>
          </div>
          <div class="select_right">
            <span v-if="addressText" class="select_right_text" style="color: #686666;">{{ addressText }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_address_home') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--      婚姻状况-->
        <div class="content_item" @click="maritalClick" v-if="resourcesShow['maritalStatus'] === 1">
          <div>
            <img class="image" src="../../assets/icon_zhuzhai.png">
            <span class="text">{{ $t('marital_status') }}</span>
          </div>
          <div class="select_right">
            <span v-if="maritalText" class="select_right_text" style="color: #686666;">{{ maritalText }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_marital_status') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--      子女个数-->
        <div class="content_item" @click="childClick" v-if="resourcesShow['childrenNum'] === 1">
          <div>
            <img class="image" src="../../assets/icon_zhuzhai.png">
            <span class="text">{{ $t('childs') }}</span>
          </div>
          <div class="select_right">
            <span v-if="childText" class="select_right_text" style="color: #686666;">{{ childText }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_chidls') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--      学历-->
        <div class="content_item" @click="ducationClick" v-if="resourcesShow['degree'] === 1">
          <div>
            <img class="image" src="../../assets/icon_zhuzhai.png">
            <span class="text">{{ $t('ducation') }}</span>
          </div>
          <div class="select_right">
            <span v-if="ducationText" class="select_right_text" style="color: #686666;">{{ ducationText }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_ducation') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--        电子邮件-->
        <div class="content_item" v-if="resourcesShow['mael'] === 1">
          <div>
            <img class="image" src="../../assets/icon_card_mumber.png">
            <span class="text">{{ $t('e_email') }}</span>
          </div>
          <input class="input" v-model="mael" :placeholder="$t('hint_input_email')"/>
        </div>
        <!--        Zalo-->
        <div class="content_item" v-if="resourcesShow['zalo'] === 1">
          <div>
            <img class="image" src="../../assets/icon_contacts_name.png">
            <span class="text">Zalo</span>
          </div>
          <input class="input" v-model="zalo" :placeholder="$t('hint_input_zalo')"/>
        </div>
        <!--        Facebook-->
        <div class="content_item" v-if="resourcesShow['facebook'] === 1">
          <div>
            <img class="image" src="../../assets/icon_contacts_name.png">
            <span class="text">Facebook</span>
          </div>
          <input class="input" v-model="facebook" :placeholder="$t('hint_input_facebook')"/>
        </div>
        <!--        贷款用途选择面板-->
        <van-action-sheet v-model:show="purposeLoanShow">
          <van-picker @confirm="purposeLoanConfirm" @cancel="purposeLoanShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="purposeLoanColumns"/>
        </van-action-sheet>

        <!--        婚姻状况选择-->
        <van-action-sheet v-model:show="maritalShow">
          <van-picker @confirm="maritalConfirm" @cancel="maritalShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="maritalColumns"/>
        </van-action-sheet>
        <!--      子女个数选择面板-->
        <van-action-sheet v-model:show="childShow">
          <van-picker @confirm="childConfirm" @cancel="childShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="childColumns"/>
        </van-action-sheet>
        <!--        学历选择面板-->
        <van-action-sheet v-model:show="ducationShow">
          <van-picker @confirm="ducationConfirm" @cancel="ducationShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="ducationColumns"/>
        </van-action-sheet>
        <!--        地址下拉选择-->
        <van-action-sheet v-model:show="addressShow">
          <div class="address_header">
            <div class="operation">
              <div class="cancel" @click="addressShow = false">{{ $t('cancel') }}</div>
              <div class="confirm" @click="addressConfirm">{{ $t('sure') }}</div>
            </div>
            <div class="input">
              <input v-model="detailsAddress" :placeholder="$t('hint_input_address_details')"/>
            </div>
          </div>
          <van-cascader
              v-model="addressValue"
              :options="addressColumns"
              :closeable="false"
              :field-names="{
                  text: 'name',
                  value: 'id',
                  children: 'children',
              }"
              @change="addressChange"
              @finish="addressFinish"
          />
        </van-action-sheet>
      </div>
      <div class="confirm">
        <button @click="confirm">{{ $t('finish') }}</button>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, toRefs, reactive} from 'vue'
import {useI18n} from 'vue-i18n'
import {Toast} from 'vant'
import {personalInfoSelect, selectCitys, savePersonalInfo} from '@/api/home'
import {debounce, processNext, setResourcesShow} from '@/utils/tool'
import {useRoute} from "vue-router";
import eventBus from "vue3-eventbus";
import {useStore} from "vuex";

export default {
  setup() {
    const {tm} = useI18n()
    const store = useStore()
    const currentDate = ref(new Date())
    // 所有下拉
    let allSelectData = ref([])
    const routes = useRoute()
    const resourcesShow = ref({})
    let userContact = reactive({
      mael: '',
      zalo: ' ',
      facebook: ' ',
    })
    // 选择贷款用途
    let purposeLoanSheet = reactive({
      purposeLoanShow: false,
      purposeLoanText: '',
      purposeLoanColumns: [],
      purposeLoanKey: null,
      purposeLoanConfirm: (value) => {
        purposeLoanSheet.purposeLoanText = value.value
        purposeLoanSheet.purposeLoanKey = value.key
        purposeLoanSheet.purposeLoanShow = false
      },
      purposeLoanClick: () => {
        purposeLoanSheet.purposeLoanShow = true
        purposeLoanSheet.purposeLoanColumns = allSelectData.value.filter(item => item.type === 1)
      }
    })
    // 选择地址
    let addressSheet = reactive({
      addressShow: false,
      addressText: '',
      addressColumns: [],
      detailsAddress: '',
      addressValue: '',
      addressFinishText: '',
      addressConfirm: () => {
        let {addressFinishText, detailsAddress} = addressSheet
        if (addressSheet.detailsAddress.length < 5) return Toast({message: tm('hint_address_to_five')})
        addressSheet.addressText = addressFinishText + ' - ' + detailsAddress
        addressSheet.addressShow = false
      },
      addressClick: async () => {
        addressSheet.addressColumns = await getCitySelect(0)
        addressSheet.addressShow = true
      },
      addressChange: async ({value}) => {
        const filterList = async (data) => {
          for (let i = 0; i < data.length; i++) {
            if (data[i].children && data[i].children.length) {
              filterList(data[i].children)
            }
            if (value === data[i].id) {
              const list = await getCitySelect(value)
              if (list.length !== 0) {
                data[i].children = list
              }
              return
            }
          }
        }
        filterList(addressSheet.addressColumns)
      },
      addressFinish: ({selectedOptions}) => {
        addressSheet.addressFinishText = selectedOptions.map((option) => option.name).join(' - ');
      }
    })
    const getCitySelect = async (value) => {
      const res = await selectCitys({pid: value})
      if (res.code === 1) {
        return res.data
      }
    }
    // 选择婚姻状况
    let maritalSheet = reactive({
      maritalShow: false,
      maritalText: '',
      maritalKey: null,
      maritalColumns: [],
      maritalConfirm: (value) => {
        maritalSheet.maritalText = value.value
        maritalSheet.maritalKey = value.key
        maritalSheet.maritalShow = false
      },
      maritalClick: () => {
        maritalSheet.maritalShow = true
        maritalSheet.maritalColumns = allSelectData.value.filter(item => item.type === 2)
      }
    })
    // 选择子女个数
    let childSheet = reactive({
      childShow: false,
      childText: '',
      maritalKey: null,
      childColumns: [],
      childConfirm: (value) => {
        childSheet.childText = value.value
        childSheet.childKey = value.key
        childSheet.childShow = false
      },
      childClick: () => {
        childSheet.childShow = true
        childSheet.childColumns = allSelectData.value.filter(item => item.type === 5)
      }
    })
// 选择学历信息
    let ducationSheet = reactive({
      ducationShow: false,
      ducationText: '',
      ducationKey: null,
      ducationColumns: [],
      ducationConfirm: (value) => {
        ducationSheet.ducationText = value.value
        ducationSheet.ducationKey = value.key
        ducationSheet.ducationShow = false
      },
      ducationClick: () => {
        ducationSheet.ducationShow = true
        ducationSheet.ducationColumns = allSelectData.value.filter(item => item.type === 3)
      }
    })
    const verificationInfo = () => {
      let message = ''
      const {mael, zalo, facebook} = userContact
      if (!purposeLoanSheet.purposeLoanKey && resourcesShow.value['loanUse'] === 1) return message = tm('hint_select_loan_purpose')
      if (!addressSheet.addressText && resourcesShow.value['liveDetailedAddress'] === 1) return message = tm('hint_select_address_home')
      if (!maritalSheet.maritalKey && resourcesShow.value['maritalStatus'] === 1) return message = tm('hint_select_marital_status')
      if (!childSheet.childKey && resourcesShow.value['childrenNum'] === 1) return message = tm('hint_select_chidls')
      if (!ducationSheet.ducationKey && resourcesShow.value['degree'] === 1) return message = tm('hint_select_ducation')
      if (!mael && resourcesShow.value['mael'] === 1) return message = tm('hint_input_email')
      if (!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(mael) && resourcesShow.value['mael'] === 1) return message = tm('incorrect_mailbox_format')
      if (!zalo && !facebook && resourcesShow.value['mael'] === 1 && resourcesShow.value['zalo'] === 1) return message = tm('input_zalo_facebook')
      return message
    }

    const confirm = debounce(
        async () => {
          if (!verificationInfo()) {
            const {mael, zalo, facebook} = userContact
            const params = {
              mael: mael,
              zalo: zalo || ' ',
              facebook: facebook || ' ',
              loanUse: purposeLoanSheet.purposeLoanKey,
              liveDetailedAddress: addressSheet.addressText,
              maritalStatus: maritalSheet.maritalKey,
              childrenNum: childSheet.childKey,
              degree: ducationSheet.ducationKey
            }
            const res = await savePersonalInfo(params)
            if (res.code === 1) {
              Toast({
                message: tm('submit_success')
              })
              processNext('personalInfo', routes.query.backName)
            } else {
              Toast({
                message: res.message
              })
            }
          } else {
            Toast({
              message: verificationInfo()
            })
          }
        }
    )
    //获取所有下拉
    const getSelect = async () => {
      const res = await personalInfoSelect({
        countryType: 2,
      })
      allSelectData.value = res.data
      // 回显内容
      if (localStorage.getItem('userWriteInfo')) {
        const {
          loanUse,
          degree,
          mali,
          maritalStatus,
          liveDetailedAddress,
          childrenNum,
          zalo,
          facebook
        } = JSON.parse(localStorage.getItem('userWriteInfo'))
        if (loanUse) {
          purposeLoanSheet.purposeLoanConfirm({
            value: allSelectData.value.filter(i => i.key === loanUse && i.type === 1)[0].value,
            key: loanUse
          })
        }
        if (maritalStatus) {
          maritalSheet.maritalConfirm({
            value: allSelectData.value.filter(i => i.key === maritalStatus && i.type === 2)[0].value,
            key: maritalStatus
          })
        }
        if (childrenNum) {
          childSheet.childConfirm({
            value: allSelectData.value.filter(i => i.key === childrenNum && i.type === 5)[0].value,
            key: childrenNum
          })
        }
        if (degree) {
          ducationSheet.ducationConfirm({
            value: allSelectData.value.filter(i => i.key === degree && i.type === 3)[0].value,
            key: degree
          })
        }
        addressSheet.addressText = liveDetailedAddress
        userContact.mael = mali
        userContact.zalo = zalo
        userContact.facebook = facebook
      }
    }
    // 流程显示隐藏
    const getResourcesShow = async () => {
      resourcesShow.value = await setResourcesShow(2)
      // 清除loading
      store.dispatch('changeLoading', false)
    }
    getResourcesShow()
    getSelect()
    return {
      ...toRefs(purposeLoanSheet),
      ...toRefs(addressSheet),
      ...toRefs(userContact),
      ...toRefs(maritalSheet),
      ...toRefs(childSheet),
      ...toRefs(ducationSheet),
      currentDate,
      allSelectData,
      confirm,
      resourcesShow
    }
  },
}
</script>

<style scoped lang="less">
.personalInfo {
  background-color: #f2f3f5;
  overflow: auto;

  ::v-deep .van-nav-bar {
    z-index: 1999;
    background: linear-gradient(90deg, #FF5252, #FF8244) !important;

  }

  ::v-deep .van-nav-bar .van-icon {
    color: #333333 !important;
  }

  ::v-deep .van-cascader__header {
    display: none;
  }

  .address_header {
    font-size: 16px;
    padding: 0 10px;
    box-sizing: border-box;

    .operation {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .confirm {
        color: #FF5252;
      }
    }

    .input {
      margin-top: 10px;
      width: 100%;

      input {
        box-sizing: border-box;
        width: 100%;
        height: 35px;
        border-radius: 3px;
        padding: 5px 10px;
        outline: none;
        border: solid 1px #FF5252;
      }
    }
  }

  .content_list {
    border-radius: 5px;
    height: 100%;
    width: 100%;

    .content_item {
      height: 40px;
      border-bottom: solid 1px #f2f3f5;
      background-color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 10px;

      div {
        height: 100%;
        display: flex;
        align-items: center;

        .image {
          height: 25px;
          width: 25px;
          margin-right: 10px;
        }

        .text {
          font-size: 12px;
          font-weight: 600;
        }
      }

      .select_right_text {
        color: #9D9D9D;
        font-size: 12px;
        margin-right: 5px;
      }

      .select_right {
        margin-right: 5px;
        margin-left: 5px;
        color: #333333;
        font-size: 12px;
        flex: 1;
        justify-content: flex-end;
      }

      .input {
        width: 180px;
        border: none;
        text-align: right;
        height: 25px;
        font-size: 12px;
      }
    }
  }

  .update_idcard {
    .update_item {
      margin-top: 10px;
      background-color: #ffffff;
      border-radius: 5px;
      text-align: center;
      padding: 5px;

      .image {
        height: 117.5px;
        width: 185px;

      }

      .text {
        color: #9D9D9D;
        font-size: 12px;
      }
    }
  }

  .confirm {
    margin-top: 20px;
    text-align: center;

    button {
      width: 300px;
      padding: 10px 0;
      color: #ffffff;
      border: none;
      font-size: 16px;
      background: linear-gradient(-45deg, #FF5252, #FF8C3C);
      box-shadow: 0px 4px 10px 0px rgba(255, 92, 78, 0.52);
      border-radius: 29px;
    }

  }
}
</style>
